package com.qingcloud.adminbackend.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qingcloud.adminbackend.anno.ProductApi;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.entity.config.SysDictionaryConfig;
import com.qingcloud.adminbackend.entity.equipment.*;
import com.qingcloud.adminbackend.entity.eventlog.EquipmentEventLogParams;
import com.qingcloud.adminbackend.entity.stationequipment.OptStationEquipment;
import com.qingcloud.adminbackend.entity.sysstation.StationMiniInfo;
import com.qingcloud.adminbackend.service.IEventLogService;
import com.qingcloud.adminbackend.service.ISysUserService;
import com.qingcloud.adminbackend.service.impl.BaseServiceImpl;
import com.qingcloud.adminbackend.utils.PoiExcelExport;
import com.qingcloud.adminbackend.anno.*;
import com.qingcloud.adminbackend.entity.equipment.*;
import com.qingcloud.adminbackend.service.ISysEquipmentService;
import com.qingcloud.base.annotation.LoginUser;
import com.qingcloud.base.remote.pojo.LoginUserDTO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 设备表基本信息表 前端控制器
 * </p>
 *
 * @author luozehua
 * @since 2018-11-19
 */
@RestController
@RequestMapping("/sys-equipment")
public class SysEquipmentController {

    @Resource
    private ISysEquipmentService sysEquipmentService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private BaseServiceImpl baseService;
    @Resource
    private IEventLogService eventLogService;


    @Value("${file.rootpath}")
    private String ROOTPATH;

    @ApiOperation(value = "从设备池移出", notes = "从设备池移出API")
    @PostMapping("/deleteEquipmentsByIds")
    public AjaxResult deleteOrder(@RequestBody EquipmentDTO equipmentDTO) {
        return sysEquipmentService.deleteEquipmentsByIds(equipmentDTO);
    }

    @ApiOperation(value = "获取所有气溶胶设备可用IP", notes = "获取所有气溶胶设备可用IP")
    @GetMapping("/ips")
    public AjaxResult getIps() {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysEquipmentService.getAerosolIpList());
    }

    /*@Sprint01
    @ApiOperation(value = "设备池的设备Api", notes = "设备池的设备Api",response = EquipmentBO.class)
    @PostMapping("/equipmentPool")
    public AjaxResult equipmentPool(String equipmenId) {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysEquipmentService.equipmentPool(equipmenId));
    }*/

    @ApiOperation(value = "订单关联设备Api(从设备池移入)", notes = "订单关联设备Api")
    @PostMapping("/orderToEquipment")
    public AjaxResult orderToEquipment(@RequestBody EquipmentDTO equipmentDTO, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean admin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        if (equipmentDTO.getEquipmentIds().size() == 0) {
            return new AjaxResult(WamingConstant.FAILURE, "请选择要绑定的设备");
        }
        return sysEquipmentService.orderToEquipment(equipmentDTO, userId);
    }

    /*@Sprint01
    @ApiOperation(value = "健康空气设备监测点批量导入Api", notes = "健康空气设备监测点批量导入Api")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "businessType", value = "业务类型（1：网格化，2:健康云）", defaultValue = "1", required = false, dataType = "String", paramType =
                    "query"),
            @ApiImplicitParam(name = "type", value = "1：设备监测点批量添加，2：添加设备，3：添加监测点", defaultValue = "1", required = false, dataType = "String", paramType =
                    "query"),
            @ApiImplicitParam(name = "orderId", value = "订单id", defaultValue = "1", required = false, dataType = "String", paramType = "query"),
    })
    @PostMapping("/equipmentStationExcel")
    public AjaxResult equipmentStationExcel(@ApiParam("上传的文件") MultipartFile file, String orderId, String type, String businessType,
                                            HttpServletRequest request) throws IOException, InvalidFormatException {
        if (file == null) return new AjaxResult(WamingConstant.FAILURE, "解析失败", null);
        String name = file.getOriginalFilename();// 获取上传文件名,包括路径
        long size = file.getSize();
        if ((name == null || name.equals("")) && size == 0) {
            return new AjaxResult(WamingConstant.FAILURE, "解析失败", null);
        }
        String userId = CookieUtil.getUserId(request);
        //网格化
        if ("1".equals(businessType)) {
            switch (type) {
                case "1":
                    //网格化设备监测点导入
                    return sysEquipmentService.equipmentStationExcelWGH(file, orderId, userId);
                case "2":
                    //设备导入
                    return sysEquipmentService.equipmentExcel(file, orderId, userId);
                default:
                    //网格化监测点导入
                    return sysEquipmentService.stationExcel(file, orderId, userId);
            }
        }
        //健康空气
        if ("2".equals(businessType)) {
            switch (type) {
                case "1":
                    //健康空气设备监测点导入
                    return sysEquipmentService.equipmentStationExcelJKKQ(file, orderId, userId);
                case "2":
                    //设备导入
                    return sysEquipmentService.equipmentExcel(file, orderId, userId);
                default:
                    //健康空气监测点导入
                    return sysEquipmentService.stationExcelJKKQ(file, orderId, userId);
            }
        }
        return new AjaxResult(WamingConstant.FAILURE, "请传入业务种类");
    }*/

    @ApiOperation(value = "从设备池批量导入Api", notes = "从设备池批量导入Api")
    @PostMapping("/equipmentPoolExcel")
    public AjaxResult equipmentPoolExcel(@RequestParam("filename") MultipartFile file, String orderId,
                                         HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) throws IOException, InvalidFormatException {
        if (file == null) return new AjaxResult(WamingConstant.FAILURE, "解析失败", null);
        String name = file.getOriginalFilename();// 获取上传文件名,包括路径
        long size = file.getSize();
        if ((name == null || name.equals("")) && size == 0) {
            return new AjaxResult(WamingConstant.FAILURE, "解析失败", null);
        }
        String userId = loginUserDTO.getUserId();
        boolean admin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        return sysEquipmentService.equipmentPoolExcel(file, orderId, userId);
    }

    @ApiOperation(value = "查询没有绑定的设备", notes = "查询没有绑定的设备", response = UnbindEquipmentDTO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID", dataType = "string", paramType = "path", defaultValue = "12ff09d5ed3b49ffad5690b1e5c53f5d"),
            @ApiImplicitParam(name = "currentPage", value = "当前第几页", dataType = "int", paramType = "path", defaultValue = "1"),
            @ApiImplicitParam(name = "prePage", value = "每页的数据量", dataType = "int", paramType = "path", defaultValue = "10")
    })
    @GetMapping("/findUnbindEquipment/{orderId}/{currentPage}/{prePage}")
    public AjaxResult findUnbindEquipment(@PathVariable("orderId") String orderId, @PathVariable("currentPage") Integer currentPage,
                                          @PathVariable("prePage") Integer prePage) {
        IPage<UnbindEquipmentDTO> unbindEquipmentDTO = sysEquipmentService.findUnbindEquipment(currentPage, prePage, orderId);
        return new AjaxResult(WamingConstant.SUCCESS, "", unbindEquipmentDTO);
    }

    @ApiOperation(value = "设备解除绑定", notes = "设备解除绑定")
    @PostMapping("/unbind")
    public AjaxResult unbind(@RequestBody @Valid OptStationEquipment sysStationEquipment, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        if (StrUtil.isNotBlank(sysStationEquipment.getStationId())) {
            sysStationEquipment.setStationId(URLUtil.decode(sysStationEquipment.getStationId()));
        }
        int un = sysEquipmentService.unbind(sysStationEquipment, userId);
        if (un == -1) {
            return new AjaxResult(WamingConstant.FAILURE, "存在次设备，不能解绑主设备！", "");
        }
        return new AjaxResult(WamingConstant.SUCCESS, "解绑成功", "");
    }


    @ApiOperation(value = "设备绑定", notes = "设备绑定")
    @PostMapping("/bind")
    public AjaxResult bind(@RequestBody @Valid OptStationEquipment sysStationEquipment, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        if (StrUtil.isNotBlank(sysStationEquipment.getStationId())) {
            sysStationEquipment.setStationId(URLUtil.decode(sysStationEquipment.getStationId()));
        }
        Integer bind = sysEquipmentService.bind(sysStationEquipment, userId);
        if (bind == -1) {
            return new AjaxResult(WamingConstant.FAILURE, "设备已被绑定", "");
        } else if (bind == -2) {
            return new AjaxResult(WamingConstant.FAILURE, "设备已不存在", "");
        } else if (bind == -3) {
            return new AjaxResult(WamingConstant.FAILURE, "该监测点已绑定过该产品类型的设备！", "");
        } else if (bind == -4) {
            return new AjaxResult(WamingConstant.FAILURE, "站点主设备已存在！", "");
        } else if (bind == -5) {
            return new AjaxResult(WamingConstant.FAILURE, "站点需先绑定一个主设备！", "");
        } else {
            return new AjaxResult(WamingConstant.SUCCESS, "", "绑定成功");
        }

    }

    @ApiOperation(value = "更换主设备绑定", notes = "更换主设备绑定")
    @PostMapping("/replaceBind")
    public AjaxResult replaceBind(@RequestBody @Valid OptStationEquipment sysStationEquipment, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean admin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        Integer bind = sysEquipmentService.replaceBind(sysStationEquipment, userId);
        if (bind == -1) {
            return new AjaxResult(WamingConstant.FAILURE, "设备已被绑定", "");
        } else if (bind == -2) {
            return new AjaxResult(WamingConstant.FAILURE, "设备已不存在", "");
        } else if (bind == -3) {
            return new AjaxResult(WamingConstant.FAILURE, "设置主设备异常!" + sysStationEquipment.getEquipmentId(), "");
        } else if (bind == -4) {
            return new AjaxResult(WamingConstant.FAILURE, "取消原主设备状态异常!" + sysStationEquipment.getEquipmentId(), "");
        } else {
            return new AjaxResult(WamingConstant.SUCCESS, "", "更换成功");
        }
    }

    @ApiOperation(value = "更换绑定", notes = "更换绑定")
    @PostMapping("/changeBind")
    public AjaxResult changeBind(@RequestBody @Valid OptStationEquipment sysStationEquipment, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean admin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        Integer bind = sysEquipmentService.changeBind(sysStationEquipment, userId);
        if (bind == -1) {
            return new AjaxResult(WamingConstant.FAILURE, "设备已被绑定", "");
        } else if (bind == -2) {
            return new AjaxResult(WamingConstant.FAILURE, "设备已不存在", "");
        } else {
            return new AjaxResult(WamingConstant.SUCCESS, "", "更换成功");
        }
    }


    @ApiOperation(value = "获取可用工作模式", notes = "获取可用工作模式")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "equipmentId", value = "设备编号", dataType = "string", paramType = "query")
    })
    @PostMapping("/findEnableWorkMode")
    public AjaxResult<List<SysDictionaryConfig>> findWorkMode(@RequestParam("equipmentId") String equipmentId) {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysEquipmentService.findEnableWorkMode(equipmentId));
    }


    @ApiOperation(value = "分页查询设备管理列表", notes = "分页查询设备管理列表", response = EquipmentListDTO.class)
    @PostMapping(value = "/findEquipmentList")
    public AjaxResult<IPage<EquipmentListDTO>> findPageEquipmentList(@RequestBody EquipmentListPara equipmentListPara, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean isAdmin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        // 完全管理权限
        boolean isFullAdmin = sysUserService.isFullAdmin(userId);

        return new AjaxResult(WamingConstant.SUCCESS, "", sysEquipmentService.listEquipment(equipmentListPara, userId, isAdmin, isFullAdmin));
    }


    @ApiOperation(value = "更新设备信息", notes = "更新设备信息")
    @PostMapping("/opt")
    public AjaxResult optEquipment(@RequestBody AddEquipmentDTO addEquipmentDTO, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean admin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        Integer flag = sysEquipmentService.optEquipment(addEquipmentDTO, userId);
        if (flag == 2) {
            return new AjaxResult(WamingConstant.SUCCESS, "", "添加成功");
        } else if (flag == -2) {
            return new AjaxResult(WamingConstant.FAILURE, "添加失败", "");
        } else if (flag == 3) {
            return new AjaxResult(WamingConstant.SUCCESS, "", "修改成功");
        } else if (flag == -3) {
            return new AjaxResult(WamingConstant.FAILURE, "修改失败", "");
        } else if (flag == -4) {
            return new AjaxResult(WamingConstant.FAILURE, "监测因子重复", "");
        } else if (flag == -5) {
            return new AjaxResult(WamingConstant.FAILURE, "设备编号已存在", "");
        } else if (flag == -6) {
            return new AjaxResult(WamingConstant.FAILURE, "订单已不存在", "");
        } else if (flag == -7) {
            return new AjaxResult(WamingConstant.FAILURE, "未检测到机器人，基础信息同步失败！", "");
        } else {
            return new AjaxResult(WamingConstant.FAILURE, "操作失败", "");
        }
    }

    @ApiOperation(value = "删除设备", notes = "删除设备")
    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody List<String> equipmentIds, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean admin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        Integer flag = sysEquipmentService.detele(equipmentIds, userId);
        if (flag == -1) {
            return new AjaxResult(WamingConstant.FAILURE, "请选择要删除的设备", "");
        } else if (flag == -2) {
            return new AjaxResult(WamingConstant.FAILURE, "该设备为站点主设备，请先解绑", "");
        } else {
            return new AjaxResult(WamingConstant.SUCCESS, "", "删除成功");
        }
    }


    @ApiOperation(value = "设备基本信息", notes = "设备基本信息", response = SysEquipmentDetailsDTO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "equipmentId", value = "设备编号", dataType = "string", paramType = "query")
    })
    @PostMapping("/equipmentDetails")
    public AjaxResult<SysEquipmentDetailsDTO> equipmentDetails(String equipmentId, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean isAdmin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        return new AjaxResult(WamingConstant.SUCCESS, "", sysEquipmentService.equipmentDetails(equipmentId, userId, isAdmin));
    }

    @ApiOperation(value = "修改设备状态", notes = "修改设备状态")
    @PostMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestBody EquipmentStatusDTO equipmentStatusDTO, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean admin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        Integer flag = sysEquipmentService.updateStatus(equipmentStatusDTO.getEquipmentIds(), equipmentStatusDTO.getStatus(), userId);
        if (flag == -1) {
            return new AjaxResult(WamingConstant.FAILURE, "请选择设备", "");
        } else if (flag > 0) {
            return new AjaxResult(WamingConstant.SUCCESS, "", "修改成功");
        } else {
            return new AjaxResult(WamingConstant.FAILURE, "修改失败", "");
        }
    }

    @ApiOperation(value = "修改校准状态", notes = "修改校准状态")
    @PostMapping("/updateVerifyStatus")
    public AjaxResult updateVerifyStatus(@RequestBody List<String> equipmentIds, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean admin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        Integer flag = sysEquipmentService.updateVerifyStatus(equipmentIds, userId);
        if (flag == -1) {
            return new AjaxResult(WamingConstant.FAILURE, "请选择设备", "");
        } else if (flag > 0) {
            return new AjaxResult(WamingConstant.SUCCESS, "", "校准成功");
        } else {
            return new AjaxResult(WamingConstant.FAILURE, "校准失败", "");
        }
    }

    @ApiOperation(value = "修改校准状态", notes = "修改校准状态")
    @PostMapping("/updateVerifyStatusByFile")
    public AjaxResult updateVerifyStatusByFile(@RequestParam("excelFile") MultipartFile excelFile, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean admin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        return sysEquipmentService.updateVerifyStatusByFile(excelFile, userId);
    }

    @ApiOperation(value = "修改IP", notes = "修改IP")
    @PostMapping("/updateIps")
    public AjaxResult updateIps(@RequestBody UpdateEquipmentIdDTO updateEquipmentIdDTO, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean admin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        Integer flag = sysEquipmentService.updateIps(updateEquipmentIdDTO, userId);
        if (flag == -1) {
            return new AjaxResult(WamingConstant.FAILURE, "选中设备的协议不同，不能同时进行设备控制操作。", "");
        } else if (flag == -2) {
            return new AjaxResult(WamingConstant.FAILURE, "请选择设备", "");
        } else if (flag == -3) {
            return new AjaxResult(WamingConstant.FAILURE, "IP地址输入有误！", "");
        } else if (flag == -4) {
            return new AjaxResult(WamingConstant.FAILURE, "域名或端口不能为空！", "");
        } else if (flag == -5) {
            return new AjaxResult(WamingConstant.FAILURE, "机器人设置ip失败！", "");
        } else {
            return new AjaxResult(WamingConstant.SUCCESS, "", "修改成功");
        }
    }

    @ApiOperation(value = "设备控制", notes = "设备控制")
    @PostMapping("/equipmentControl")
    public AjaxResult equipmentControl(@RequestBody List<String> equipmentIds, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean admin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        Integer flag = sysEquipmentService.equipmentControl(equipmentIds, userId);
        if (flag == -2) {
            return new AjaxResult(WamingConstant.FAILURE, "请选择设备", "");
        } else if (flag == -1) {
            return new AjaxResult(WamingConstant.FAILURE, "选中设备的协议不同，不能同时进行设备控制操作。", "");
        } else if (flag == -3) {
            return new AjaxResult(WamingConstant.FAILURE, "不支持对选中设备进行设备控制操作。", "");
        } else if (flag == 1) {
            return new AjaxResult(WamingConstant.SUCCESS, "", WamingConstant.PROTOCOL_CODE_MQTT);
        } else if (flag == 3) {
            return new AjaxResult(WamingConstant.SUCCESS, "", WamingConstant.PROTOCOL_CODE_WT);
        } else {
            return new AjaxResult(WamingConstant.FAILURE, "校验失败", "");
        }
    }

    @ApiOperation(value = "设备批量导入Api", notes = "设备批量导入Api")
    @PostMapping("/equipmentExcel")
    public AjaxResult equipmentExcel(@ApiParam("上传的文件") MultipartFile file,
                                     HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) throws IOException, InvalidFormatException {
        if (file == null) return new AjaxResult(WamingConstant.FAILURE, "解析失败", null);
        String name = file.getOriginalFilename();// 获取上传文件名,包括路径
        long size = file.getSize();
        if ((name == null || name.equals("")) && size == 0) {
            return new AjaxResult(WamingConstant.FAILURE, "解析失败", null);
        }
        String userId = loginUserDTO.getUserId();
        boolean admin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        //设备导入
        return sysEquipmentService.equipmentExcelV2(file, userId);
    }

    @ApiOperation(value = "获取设备绑定监测点的情况", notes = "获取设备绑定监测点的情况", response = StationMiniInfo.class)
    @ApiImplicitParams({@ApiImplicitParam(name = "equipmentId", value = "设备编号", defaultValue = "1190100114", required = true, dataType = "String",
            paramType = "path")})
    @GetMapping("/getEqBind/{equipmentId}")
    public AjaxResult getEqBind(@PathVariable("equipmentId") String equipmentId) {
        StationMiniInfo orderBind = sysEquipmentService.getEqBind(equipmentId);
        return new AjaxResult(WamingConstant.SUCCESS, "", orderBind);
    }

    @ApiOperation(value = "导出设备列表", notes = "导出设备列表")
    @PostMapping("/export")
    public AjaxResult export(@RequestBody EquipmentListPara equipmentListPara, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean isAdmin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        // 完全管理权限
        boolean isFullAdmin = sysUserService.isFullAdmin(userId);
        String fileName = "EquipmentList-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".xlsx";
        String sheetName = "设备列表";

        String[] titleName = {"设备编号", "产品", "产品型号", "监测因子", "设备状态", "生产状态", "生产厂商", "物联网卡号", "CCID", "采集间隔", "上传间隔", "硬件版本号", "固件版本号", "监测点名称", "监测点编号", "所属订单"};// 列名
        String[] titleColumn = {"equipmentId", "productName", "productType", "sensorFactorsTips", "status", "standardFlag", "manufacturer",
                "phoneNum", "ccidNum", "collectInternel", "uploadInternel", "hardwareVersion", "softwareVersion", "stationName", "stationId", "projectName"};
        int[] titleSize = {20, 50, 20, 100, 20, 20, 50, 20, 30, 10, 10, 20, 20, 30, 20, 50};
        equipmentListPara.setCurrentPage(1);
        equipmentListPara.setPerPage(Integer.MAX_VALUE);
        List<EquipmentExportDTO> dataList = sysEquipmentService.exportData(equipmentListPara, userId, isAdmin, isFullAdmin);
        String fileDir = ROOTPATH + "/temp";
        File dir = new File(fileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String file = fileDir + "/" + fileName;
        PoiExcelExport poiExcelExport = new PoiExcelExport(file, sheetName);
        poiExcelExport.wirteExcel(titleColumn, titleName, titleSize, dataList);
        AjaxResult result = new AjaxResult();
        String url = request.getContextPath() + "/file/view/temp/" + fileName;
        Map<String, String> resultMap = new HashMap<>(1);
        resultMap.put("url", url);
        result.setResult(resultMap);
        result.setErroCode(2000);
        return result;
    }

    @ApiOperation(value = "所有可管理的设备", notes = "所有可管理的设备")
    @PostMapping(value = "/getEquipmentMgrIds")
    public AjaxResult getEquipmentMgrIdsData(@RequestBody EquipmentMgrBO equipmentMgrBO, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean admin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        List<ModelDTO> equipments = baseService.getEquipmentIds(userId, equipmentMgrBO.getOrderIds(), equipmentMgrBO.getOrgIds(), equipmentMgrBO.getStationFlag());
        List<String> list = new ArrayList<>();
        equipments.forEach(equipment -> {
            if (StrUtil.isNotBlank(equipmentMgrBO.getEquipmentId())) {
                String modelId = equipment.getModelId();
                if (modelId.indexOf(equipmentMgrBO.getEquipmentId()) >= 0) {
                    list.add(equipment.getModelId());
                }
            } else {
                list.add(equipment.getModelId());
            }
        });
        return new AjaxResult(WamingConstant.SUCCESS, "", list);
    }

    @ApiOperation(value = "所有设备无权限", notes = "所有设备无权限")
    @PostMapping(value = "/getAllEquipmentIds")
    public AjaxResult getAllEquipmentIdsWithoutPermission(@RequestBody EquipmentMgrBO equipmentMgrBO, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean isAdmin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        IPage<ModelDTO> equipments = baseService.getEquipmentIdsPage(userId, equipmentMgrBO);
        equipments.getRecords().forEach(it -> {
            it.setShowValue(it.getModelId() + " | " + it.getProductType());
        });
        return new AjaxResult(WamingConstant.SUCCESS, "", equipments);
    }

    @ApiOperation(value = "设备是否存在", notes = "设备是否存在")
    @GetMapping(value = "/existEquipment")
    public AjaxResult existEquipment(@RequestParam("equipmentId") String equipmentId) {
        Long count = sysEquipmentService.existEquipment(equipmentId);
        if (count > 0)
            return new AjaxResult(WamingConstant.SUCCESS, "设备存在", count);
        else
            return new AjaxResult(WamingConstant.SUCCESS, "设备不存在", 0);
    }


    @ApiOperation(value = "设备事件列表", notes = "设备事件列表")
    @PostMapping(value = "/equipmentEvent")
    public AjaxResult equipmentEvent(@RequestBody EquipmentEventLogParams equipmentEventLogParams, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean admin = loginUserDTO.getIsAdmin() == 1 ? true : false;
        return new AjaxResult(WamingConstant.SUCCESS, null, eventLogService.listEquipmentEventLog(equipmentEventLogParams));
    }

    @ApiOperation(value = "设备日志获取列表下拉框搜索条件", notes = "获取列表下拉框搜索条件")
    @PostMapping(value = "/getSelectData")
    public AjaxResult getSelectData() {
        Map<String, Object> resultMap = new HashMap<>();
        //故障类型
        List<SysDictionaryConfig> faultType = eventLogService.findDeviceTypeByType(WamingConstant.DICTIONARYTYPE_FAULT_TYPE);
        resultMap.put("faultType", faultType);
        //事件类型
        List<SysDictionaryConfig> eventType = eventLogService.findDeviceTypeByType(WamingConstant.DICTIONARYTYPE_EVENT_TYPE);
        resultMap.put("eventType", eventType);

        //复位原因
        List<SysDictionaryConfig> resetType01 = eventLogService.findDeviceTypeByType(WamingConstant.DICTIONARYTYPE_RESET_TYPE01);
        List<SysDictionaryConfig> resetType02 = eventLogService.findDeviceTypeByType(WamingConstant.DICTIONARYTYPE_RESET_TYPE02);
        resetType01.addAll(resetType02);
        resultMap.put("resetType", resetType01);
        return new AjaxResult(WamingConstant.SUCCESS, null, resultMap);
    }

    @ProductApi
    @ApiOperation(value = "设备网关信息", notes = "设备网关信息")
    @GetMapping(value = "/gateway")
    public AjaxResult equipmentGateway(@RequestParam("equipmentId") String equipmentId) {
        return AjaxResult.ok(sysEquipmentService.gatewayInfo(equipmentId));
    }

    @ProductApi
    @ApiOperation(value = "查询设备解码器", notes = "查询设备解码器")
    @GetMapping(value = "/decoders")
    public AjaxResult decoders(@RequestParam("equipmentId") String equipmentId) {
        return AjaxResult.ok(sysEquipmentService.decoders(equipmentId));
    }

    @ProductApi
    @ApiOperation(value = "查询设备解码器消息", notes = "查询设备解码器消息")
    @GetMapping(value = "/decode/message")
    public AjaxResult decodeMessage(@RequestParam("equipmentId") String equipmentId,
                                    @RequestParam("componentId") Integer componentId) {
        return AjaxResult.ok(sysEquipmentService.decodeMessage(equipmentId, componentId));
    }
}
